package com.accounting.client.frontend.product.search;

import java.util.List;

import com.accounting.client.ApplicationContext;
import com.accounting.client.frontend.common.CurrencyBox;
import com.accounting.client.remote.Services;
import com.accounting.client.remote.enumeration.StockLocation;
import com.accounting.client.remote.obj.Product;
import com.accounting.client.remote.obj.PurchaseRecord;
import com.accounting.client.remote.obj.User;
import com.accounting.client.remote.transfer.SearchPurchaseRecordRequest;
import com.accounting.client.session.ErrorHandler;
import com.accounting.client.session.SessionManager;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;

import corelib.client.Util;
import corelib.client.search.JSONSearchRequest;
import corelib.client.search.PagingRequest;
import corelib.client.search.PagingResult;
import corelib.client.ui.SimpleMask;
import corelib.client.ui.widget.WidgetListener;
import corelib.client.ui.widget.button.Button;
import corelib.client.ui.widget.form.DateBox;
import corelib.client.ui.widget.form.LazyInitializer;
import corelib.client.ui.widget.form.SelectField;
import corelib.client.ui.widget.form.fomatters.ValueFormatter;
import corelib.client.ui.widget.grid.SimpleDataGrid;
import corelib.client.ui.widget.layout.RelativeColumn;
import corelib.client.ui.widget.panel.SimpleSearchPanel;

public class PurchaseRecordSearchPanel extends SimpleSearchPanel {
	
	private SelectField<StockLocation> locationField;
	private SelectField<Product>       productField;
	private CurrencyBox 			 priceField;
	private DateBox 				 dateCreatedField;
	private SelectField<User> 	     operatorField;
	private SelectField<User> 		 postOperatorField;
	
	private SimpleDataGrid<PurchaseRecord> table;
	
	public PurchaseRecordSearchPanel(SimpleDataGrid<PurchaseRecord> grid){
		this.table = grid;
	}
	
	@Override
	protected Widget getMaskWidget() {
		return table;
	}
	
	@Override
	protected void afterCreateWidget(Panel w) {
		super.afterCreateWidget(w);
		
		PagingRequest request = new PagingRequest();
		request.setOffset(0);
		request.setLimit(1000);
		request.setKeyword(Util.EMPTY_STRING);
		
		Services.ProductService.ListProductsByKeyword(SessionManager.getPassport(), 
			request, 
			new AsyncCallback<PagingResult<Product>>(){
			@Override
			public void onFailure(Throwable caught) {
				ErrorHandler.handleServiceError(caught);
			}
			
			@Override
			public void onSuccess(PagingResult<Product> result) {
				productField.setOptions(result.getData());
			}
		});
	}

	@Override
	protected Widget createContentPanel() {
		
		priceField       = new CurrencyBox();
		dateCreatedField = new DateBox();
		locationField    = new SelectField<StockLocation>(StockLocation.All);
		locationField.setNullable(true);
		locationField.setOptionFormatter("请选择库存位置", new ValueFormatter<StockLocation>(){
			@Override
			public String format(StockLocation value) {
				return value.getCname();
			}
		});
		
		productField = new SelectField<Product>();
		productField.setNullable(true);
		productField.setOptionFormatter("请选择产品", new ValueFormatter<Product>(){
			@Override
			public String format(Product value) {
				return value.getCName();
			}
		});
		
		operatorField = new SelectField<User>(ApplicationContext.getAllUsers());
		operatorField.setNullable(true);
		operatorField.setOptionFormatter("请选择购买员", new ValueFormatter<User>(){
			@Override
			public String format(User value) {
				return value.getCName();
			}
		});
		
		postOperatorField = new SelectField<User>(ApplicationContext.getAllUsers());
		postOperatorField.setNullable(true);
		postOperatorField.setOptionFormatter("请选择邮寄员", new ValueFormatter<User>(){
			@Override
			public String format(User value) {
				return value.getCName();
			}
		});
		
		int lw  = 100;
		int fw  = 150;
		int gap = 12;
		
		FlowPanel panel = new FlowPanel();
		panel.getElement().getStyle().setPadding(10, Unit.PX);
		RelativeColumn col = new RelativeColumn();
		col.setRowSpacing(12);
		
		col.addRow()
		   .add(LazyInitializer.createLabel("购买单价").setBold(true), lw + fw + gap);
		
		col.addRow()
		   .add(priceField, lw + gap +fw);
		
		col.addRow()
		   .add(LazyInitializer.createLabel("购买日期").setBold(true), lw + fw + gap);
		
		col.addRow()
		   .add(dateCreatedField, lw + gap +fw);
		
		col.addRow()
		   .add(LazyInitializer.createLabel("选择产品").setBold(true),lw + fw + gap);
		
		col.addRow()
		   .add(productField, lw + gap +fw);
		
		col.addRow()
		   .add(LazyInitializer.createLabel("购买员").setBold(true),130)
		   .addSpace(gap)
		   .add(LazyInitializer.createLabel("邮寄员").setBold(true),120);
		
		col.addRow()
		   .add(operatorField, 130)
		   .addSpace(gap)
		   .add(postOperatorField, 120);
		
		col.addRow()
		   .add(LazyInitializer.createLabel("库存位置").setBold(true),lw + fw + gap);
		
		col.addRow()
		   .add(locationField, lw + gap +fw);
		
		Button searchButton = new Button("搜索", new WidgetListener(){
			@Override
			public void valueUpdated(Widget widget) {
				search();
			}
		});
		
		Button resetButton = new Button("重置", new WidgetListener(){
			@Override
			public void valueUpdated(Widget widget) {
				reset();
				search();
			}
		});
		
		col.addRow().add(searchButton, 100).addSpace(gap).add(resetButton, 100);
		panel.add(col.getPanel());
		return panel;
	}
	
	public void reset() {
		dateCreatedField.reset();
		postOperatorField.setSelectedOption(null);
		operatorField.setSelectedOption(null);
		priceField.setDouble(null);
		locationField.setSelectedOption(null);
		productField.setSelectedOption(null);
	}
	
	public SearchPurchaseRecordRequest getRequest(){
		Integer location = locationField.getSelectedOption() 
						== null 
						 ? null 
						 : locationField.getSelectedOption().getLocation();
		
		String operatorId = operatorField.getSelectedOption() 
						 == null
						  ? Util.EMPTY_STRING
						  : operatorField.getSelectedOption().getUserId();
		
		String postOperatorId = postOperatorField.getSelectedOption() 
							 == null
							  ? Util.EMPTY_STRING
							  : postOperatorField.getSelectedOption().getUserId();
		
		SearchPurchaseRecordRequest request = new SearchPurchaseRecordRequest();
		request.setOperatorId(operatorId);
		request.setPostOperatorId(postOperatorId);
		request.setOffset(0);
		request.setLimit(1000);
		request.setLocation(location);
		request.setPrice(priceField.getDouble());
		request.setPurchaseDate(dateCreatedField.getDate());
		
		if (productField.getSelectedOption() == null){
			request.setProductName(Util.EMPTY_STRING);
		}
		else {
			request.setProductName(productField.getSelectedOption().getCName());
		}
		return request;
	}
	
	public void search() {
		SearchPurchaseRecordRequest request = getRequest();
		SimpleMask.show(getMaskWidget(), "努力搜索中...");
		Services.ProductService.SearchPurchaseRecords(SessionManager.getPassport(), 
		    request, 
		    new AsyncCallback<PagingResult<PurchaseRecord>>(){
			@Override
			public void onFailure(Throwable caught) {
				SimpleMask.hide(getMaskWidget());
				ErrorHandler.handleServiceError(caught);
			}
			@Override
			public void onSuccess(PagingResult<PurchaseRecord> result) {
				SimpleMask.hide(getMaskWidget());
				table.setObjects(result.getData());
			}
		});
	}
	
	@Override
	protected JSONSearchRequest createSearchRequest() {
		return new JSONSearchRequest();
	}
	
}
